package com.hello.system.controller.app;

import java.util.List;
import java.math.BigDecimal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.transaction.annotation.Transactional;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.common.security.utils.SecurityUtils;
import com.hello.system.domain.RentalSuppliers;
import com.hello.system.domain.RentalDeviceProducts;
import com.hello.system.service.IRentalSuppliersService;
import com.hello.system.service.IRentalDeviceProductsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * App端供应商信息接口
 * 
 * @author hello
 * @date 2025-01-03
 */
@Slf4j
@RestController
@RequestMapping("/app/supplier")
@RequiredArgsConstructor
public class AppSupplierController extends BaseController
{
    private final IRentalSuppliersService rentalSuppliersService;
    private final IRentalDeviceProductsService rentalDeviceProductsService;

    /**
     * 根据token获取我的供应商信息（App端专用）
     * 
     * @return 当前用户的供应商信息
     */
    @GetMapping("/profile")
    public AjaxResult getSupplierProfile()
    {
        Long userId = SecurityUtils.getUserId();
        log.info("======== 获取供应商资料请求 ========");
        log.info("用户ID: {}", userId);
        
        // 根据用户ID查询供应商信息
        RentalSuppliers queryParam = new RentalSuppliers();
        queryParam.setUserId(userId);
        
        List<RentalSuppliers> supplierList = rentalSuppliersService.selectRentalSuppliersList(queryParam);
        log.info("查询到的供应商数量: {}", supplierList.size());
        
        if (supplierList.isEmpty()) {
            log.info("用户 {} 尚未注册为供应商", userId);
            return AjaxResult.success("尚未注册为供应商", null);
        }
        
        // 返回第一个供应商信息（通常一个用户只有一个供应商身份）
        RentalSuppliers supplier = supplierList.get(0);
        log.info("返回供应商信息: {}", supplier.getSupplierName());
        
        return AjaxResult.success("获取供应商信息成功", supplier);
    }

    /**
     * 申请成为供应商（App端专用）
     * 
     * @param rentalSuppliers 供应商申请信息
     * @return 申请结果
     */
    @PostMapping("/apply")
    @Transactional
    public AjaxResult applySupplier(@RequestBody RentalSuppliers rentalSuppliers)
    {
        Long userId = SecurityUtils.getUserId();
        log.info("======== 供应商申请请求 ========");
        log.info("用户ID: {}, 申请类型: {}", userId, rentalSuppliers.getSupplierType());
        
        // 检查用户是否已经申请过供应商
        RentalSuppliers queryParam = new RentalSuppliers();
        queryParam.setUserId(userId);
        
        List<RentalSuppliers> existingSuppliers = rentalSuppliersService.selectRentalSuppliersList(queryParam);
        if (!existingSuppliers.isEmpty()) {
            log.warn("用户 {} 已经申请过供应商", userId);
            return AjaxResult.error("您已经申请过供应商，请勿重复申请");
        }
        
        // 设置申请信息
        rentalSuppliers.setUserId(userId);
        rentalSuppliers.setCreateBy(userId.toString());
        rentalSuppliers.setApplicationStatus(1); // 申请中
        rentalSuppliers.setAuditStatus(0); // 待审核
        rentalSuppliers.setStatus(0); // 待激活
        rentalSuppliers.setCertificationStatus(0); // 未认证
        rentalSuppliers.setCommissionRate(new BigDecimal("0.03")); // 默认3%佣金
        
        // 生成供应商编码
        String supplierCode = "SUP" + System.currentTimeMillis();
        rentalSuppliers.setSupplierCode(supplierCode);
        
        int result = rentalSuppliersService.insertRentalSuppliers(rentalSuppliers);
        
        if (result > 0) {
            log.info("用户 {} 供应商申请提交成功", userId);
            return AjaxResult.success("供应商申请提交成功，请等待审核");
        } else {
            log.error("用户 {} 供应商申请提交失败", userId);
            return AjaxResult.error("申请提交失败，请稍后重试");
        }
    }

    /**
     * 更新我的供应商信息（App端专用）
     * 
     * @param rentalSuppliers 供应商更新信息
     * @return 更新结果
     */
    @PutMapping("/update")
    @Transactional
    public AjaxResult updateSupplierProfile(@RequestBody RentalSuppliers rentalSuppliers)
    {
        Long userId = SecurityUtils.getUserId();
        log.info("======== 更新供应商信息请求 ========");
        log.info("用户ID: {}", userId);
        
        // 验证供应商是否属于当前用户
        RentalSuppliers existingSupplier = rentalSuppliersService.selectRentalSuppliersBySupplierId(rentalSuppliers.getSupplierId());
        if (existingSupplier == null) {
            log.warn("供应商信息不存在: {}", rentalSuppliers.getSupplierId());
            return AjaxResult.error("供应商信息不存在");
        }
        
        if (!userId.equals(existingSupplier.getUserId())) {
            log.warn("用户 {} 尝试修改不属于自己的供应商信息: {}", userId, rentalSuppliers.getSupplierId());
            return AjaxResult.error("无权限修改该供应商信息");
        }
        
        // 设置更新信息
        rentalSuppliers.setUpdateBy(userId.toString());
        
        int result = rentalSuppliersService.updateRentalSuppliers(rentalSuppliers);
        
        if (result > 0) {
            log.info("用户 {} 供应商信息更新成功", userId);
            return AjaxResult.success("供应商信息更新成功");
        } else {
            log.error("用户 {} 供应商信息更新失败", userId);
            return AjaxResult.error("更新失败，请稍后重试");
        }
    }

    /**
     * 获取我的供应商产品列表（App端专用）
     * 
     * @return 当前供应商的产品列表
     */
    @GetMapping("/products")
    public AjaxResult getSupplierProducts()
    {
        Long userId = SecurityUtils.getUserId();
        log.info("======== 获取供应商产品列表请求 ========");
        log.info("用户ID: {}", userId);
        
        // 先获取供应商信息
        RentalSuppliers queryParam = new RentalSuppliers();
        queryParam.setUserId(userId);
        
        List<RentalSuppliers> supplierList = rentalSuppliersService.selectRentalSuppliersList(queryParam);
        if (supplierList.isEmpty()) {
            log.info("用户 {} 不是供应商", userId);
            return AjaxResult.error("您还不是供应商，无法查看产品");
        }
        
        RentalSuppliers supplier = supplierList.get(0);
        
        // 查询该供应商的产品
        RentalDeviceProducts productQuery = new RentalDeviceProducts();
        productQuery.setSupplierId(supplier.getSupplierId());
        
        List<RentalDeviceProducts> productList = rentalDeviceProductsService.selectRentalDeviceProductsList(productQuery);
        log.info("供应商 {} 的产品数量: {}", supplier.getSupplierName(), productList.size());
        
        return AjaxResult.success("获取产品列表成功", productList);
    }

    /**
     * 获取供应商统计信息（App端专用）
     * 
     * @return 供应商统计数据
     */
    @GetMapping("/statistics")
    public AjaxResult getSupplierStatistics()
    {
        Long userId = SecurityUtils.getUserId();
        log.info("======== 获取供应商统计信息请求 ========");
        log.info("用户ID: {}", userId);
        
        // 先获取供应商信息
        RentalSuppliers queryParam = new RentalSuppliers();
        queryParam.setUserId(userId);
        
        List<RentalSuppliers> supplierList = rentalSuppliersService.selectRentalSuppliersList(queryParam);
        if (supplierList.isEmpty()) {
            log.info("用户 {} 不是供应商", userId);
            return AjaxResult.error("您还不是供应商");
        }
        
        RentalSuppliers supplier = supplierList.get(0);
        
        // 查询产品统计
        RentalDeviceProducts productQuery = new RentalDeviceProducts();
        productQuery.setSupplierId(supplier.getSupplierId());
        List<RentalDeviceProducts> productList = rentalDeviceProductsService.selectRentalDeviceProductsList(productQuery);
        
        // 构建统计信息
        java.util.Map<String, Object> statistics = new java.util.HashMap<>();
        statistics.put("supplierInfo", supplier);
        statistics.put("totalProducts", productList.size());
        
        // 统计不同状态的产品数量
        long onlineProducts = productList.stream().filter(p -> p.getStatus() == 1).count();
        long offlineProducts = productList.stream().filter(p -> p.getStatus() == 0).count();
        long auditingProducts = productList.stream().filter(p -> p.getAuditStatus() == 0).count();
        
        statistics.put("onlineProducts", onlineProducts);
        statistics.put("offlineProducts", offlineProducts);
        statistics.put("auditingProducts", auditingProducts);
        
        log.info("供应商 {} 统计信息: 总产品={}, 在线={}, 下线={}, 审核中={}", 
                supplier.getSupplierName(), productList.size(), onlineProducts, offlineProducts, auditingProducts);
        
        return AjaxResult.success("获取统计信息成功", statistics);
    }

    /**
     * 获取供应商申请状态（App端专用）
     * 
     * @return 申请状态信息
     */
    @GetMapping("/application-status")
    public AjaxResult getApplicationStatus()
    {
        Long userId = SecurityUtils.getUserId();
        log.info("======== 获取供应商申请状态请求 ========");
        log.info("用户ID: {}", userId);
        
        // 根据用户ID查询供应商申请信息
        RentalSuppliers queryParam = new RentalSuppliers();
        queryParam.setUserId(userId);
        
        List<RentalSuppliers> supplierList = rentalSuppliersService.selectRentalSuppliersList(queryParam);
        
        if (supplierList.isEmpty()) {
            log.info("用户 {} 尚未申请供应商", userId);
            java.util.Map<String, Object> status = new java.util.HashMap<>();
            status.put("hasApplication", false);
            status.put("message", "尚未申请成为供应商");
            return AjaxResult.success("查询成功", status);
        }
        
        RentalSuppliers supplier = supplierList.get(0);
        java.util.Map<String, Object> status = new java.util.HashMap<>();
        status.put("hasApplication", true);
        status.put("supplierId", supplier.getSupplierId());
        status.put("supplierName", supplier.getSupplierName());
        status.put("supplierType", supplier.getSupplierType());
        status.put("applicationStatus", supplier.getApplicationStatus());
        status.put("auditStatus", supplier.getAuditStatus());
        status.put("certificationStatus", supplier.getCertificationStatus());
        status.put("status", supplier.getStatus());
        status.put("applicationTime", supplier.getApplicationTime());
        status.put("auditTime", supplier.getAuditTime());
        status.put("auditRemark", supplier.getAuditRemark());
        
        // 状态文本说明
        String applicationStatusText = getApplicationStatusText(supplier.getApplicationStatus());
        String auditStatusText = getAuditStatusText(supplier.getAuditStatus());
        String statusText = getStatusText(supplier.getStatus());
        
        status.put("applicationStatusText", applicationStatusText);
        status.put("auditStatusText", auditStatusText);
        status.put("statusText", statusText);
        
        log.info("用户 {} 供应商申请状态: {}", userId, applicationStatusText);
        
        return AjaxResult.success("查询成功", status);
    }

    /**
     * 获取申请状态文本
     */
    private String getApplicationStatusText(Integer applicationStatus) {
        if (applicationStatus == null) return "未知";
        switch (applicationStatus) {
            case 0: return "待申请";
            case 1: return "申请中";
            case 2: return "申请通过";
            case 3: return "申请拒绝";
            default: return "未知";
        }
    }

    /**
     * 获取审核状态文本
     */
    private String getAuditStatusText(Integer auditStatus) {
        if (auditStatus == null) return "未知";
        switch (auditStatus) {
            case 0: return "待审核";
            case 1: return "审核通过";
            case 2: return "审核拒绝";
            default: return "未知";
        }
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待激活";
            case 1: return "启用";
            case 2: return "冻结";
            case 3: return "注销";
            default: return "未知";
        }
    }
}